<template>
  <div class="px-4 sm:px-8 md:px-16 lg:px-48 pt-4 w-full">
    <div class="flex flex-col">
      <n-card :title="'高校管理'">
        <template #header-extra>
          <div class="flex items-center">
            <n-button type="primary" @click="openCreateModal" class="px-6 mr-4">
              新增高校信息
            </n-button>
            <n-button type="success" @click="handleExport" :loading="isExporting" class="px-6">
              导出至Excel
            </n-button>
          </div>
        </template>

        <div style="display: flex; flex-wrap: wrap; gap: 16px; margin-top: 16px; margin-bottom: 4px; align-items: center;">
          <div style="flex-shrink: 0; width: 280px;">
            <n-input v-model:value="searchTerm" placeholder="按学校名称、代码、联系人搜索..." clearable @input="handleSearchDebounced"
              @clear="handleSearchDebounced">
              <template #prefix>
                <n-icon :component="SearchOutline" />
              </template>
            </n-input>
          </div>
          <div style="flex-shrink: 0; width: 180px;">
            <n-select v-model:value="filterGoverningDepartment" placeholder="选择主管部门" :options="governingDepartmentFilterOptions" multiple
              filterable clearable @update:value="applyTableFilters" />
          </div>
          <div style="flex-shrink: 0; width: 160px;">
            <n-select v-model:value="filterLocation" placeholder="选择所在地" :options="locationFilterOptions" multiple
              filterable clearable @update:value="applyTableFilters" />
          </div>
          <div style="flex-shrink: 0; width: 140px;">
            <n-select v-model:value="filterIsCentral" placeholder="中央直属" :options="isCentralFilterOptions"
              clearable @update:value="applyTableFilters" />
          </div>
          <div style="flex: 1;" />
        </div>

        <div style="margin-top: 0;">
          <n-data-table
            ref="dataTableInstRef"
            :columns="columns"
            :data="universityStore.allUniversities"
            :loading="universityStore.isLoading"
            :pagination="paginationConfig"
            remote
            @update:page="handlePageChange"
            @update:page-size="handlePageSizeChange"
            @update:sorter="handleSorterChange"
            class="min-w-full"
            :scroll-x="2600"
          />
        </div>
      </n-card>
    </div>

    <n-modal
      v-model:show="showModal"
      preset="card"
      :style="{ width: '900px' }"
      :title="modalTitle"
      size="huge"
      :bordered="false"
      :segmented="{ content: 'soft', footer: 'soft' }"
      closable
      @after-leave="handleModalClose"
    >
      <university-form
        ref="universityFormRef"
        :initial-data="editingUniversity"
        @submit="handleFormSubmit"
        @cancel="closeModal"
      />
    </n-modal>
  </div>
</template>

<script setup>
import { SearchOutline } from "@vicons/ionicons5";
import { h, ref, onMounted, computed } from "vue";
import {
  NIcon,
  NDataTable,
  NButton,
  useMessage,
  NInput,
  NSelect,
  NModal,
  NEllipsis,
  NCard,
  useDialog,
  NTag,
} from "naive-ui";
import UniversityForm from '@/components/UniversityForm.vue';

import { useUniversityStore } from '@/stores/universityStore';
import { booleanStatusOptions, governingDepartmentOptions, locationOptions } from '@/utils/constants';

const message = useMessage();
const dialog = useDialog();
const universityStore = useUniversityStore();

const dataTableInstRef = ref(null);

// --- Modal control for UniversityForm ---
const showModal = ref(false);
const modalTitle = ref('新增高校信息');
const editingUniversity = ref(null);
const universityFormRef = ref(null);

const openCreateModal = () => {
  editingUniversity.value = null;
  modalTitle.value = '新增高校信息';
  showModal.value = true;
};

const openEditModal = (rowData) => {
  editingUniversity.value = { ...rowData };
  modalTitle.value = '编辑高校信息';
  showModal.value = true;
};

const closeModal = () => {
  showModal.value = false;
};

const handleModalClose = () => {
  if (universityFormRef.value && typeof universityFormRef.value.resetForm === 'function') {
    universityFormRef.value.resetForm();
  }
  editingUniversity.value = null;
};

const handleFormSubmit = async (formData) => {
  // 立即关闭对话框，提升用户体验
  closeModal();

  try {
    if (editingUniversity.value && editingUniversity.value._id) {
      await universityStore.updateUniversity(editingUniversity.value._id, formData);
      message.success('高校信息更新成功');
    } else {
      await universityStore.addUniversity(formData);
      message.success('高校信息新增成功');
    }

    // 重新获取当前页数据
    await fetchUniversitiesWithFilters();
  } catch (error) {
    console.error("表单提交失败:", error);
    message.error(editingUniversity.value ? '更新失败，请重试' : '新增失败，请重试');
    // 不需要重新抛出错误，因为对话框已经关闭了
  }
};

// --- Data Mapping for Display ---
const governingDepartmentMap = Object.fromEntries(governingDepartmentOptions.map(opt => [opt.value, opt.label]));
const locationMap = Object.fromEntries(locationOptions.map(opt => [opt.value, opt.label]));
const booleanStatusMap = Object.fromEntries(booleanStatusOptions.map(opt => [opt.value, opt.label]));

const getDisplayValue = (value, map, defaultValue = '未知') => map[value] || value || defaultValue;

// Options for filters
const governingDepartmentFilterOptions = ref(governingDepartmentOptions);
const locationFilterOptions = ref(locationOptions);
const isCentralFilterOptions = ref([
  { label: '是', value: true },
  { label: '否', value: false }
]);



const createColumns = ({ onEdit, onDelete }) => {
  return [
    {
      title: '序号',
      key: 'tableId',
      width: 60,
      fixed: 'left',
      render: (_, index) => (paginationConfig.value.page - 1) * paginationConfig.value.pageSize + index + 1
    },
    { title: '学校名称', key: 'schoolName', width: 200, sorter: true, fixed: 'left', ellipsis: { tooltip: true } },
    { title: '学校标准码', key: 'schoolCode', width: 120, sorter: true, ellipsis: { tooltip: true } },
    {
      title: '主管部门', key: 'governingDepartment', width: 180, sorter: true,
      render: (row) => getDisplayValue(row.governingDepartment, governingDepartmentMap)
    },
    {
      title: '所在地', key: 'location', width: 100, sorter: true,
      render: (row) => getDisplayValue(row.location, locationMap)
    },
    {
      title: '中央直属', key: 'isCentral', width: 100, sorter: true, align: 'center',
      render: (row) => {
        const statusLabel = getDisplayValue(row.isCentral, booleanStatusMap);
        return h(NTag, { type: row.isCentral ? 'success' : 'default', bordered: false }, { default: () => statusLabel });
      }
    },
    { title: '联系部门', key: 'contactDepartment', width: 120, ellipsis: { tooltip: true } },
    { title: '联系职务', key: 'contactPosition', width: 120, ellipsis: { tooltip: true } },
    { title: '联系人', key: 'contactName', width: 100, ellipsis: { tooltip: true } },
    { title: '座机电话', key: 'landlinePhone', width: 140, ellipsis: { tooltip: true } },
    { title: '手机号码', key: 'mobilePhone', width: 140, ellipsis: { tooltip: true } },
    {
      title: '备注', key: 'remarks', width: 200,
      render: row => h(NEllipsis, { tooltip: { style: { maxWidth: '300px' } } }, { default: () => row.remarks || 'N/A' })
    },
    {
      title: '操作',
      key: 'actions',
      width: 180,
      fixed: 'right',
      render(row) {
        return h('div', { style: 'display: flex; align-items: center; justify-content: center;' }, [
          h(NButton, { size: 'small', type: 'primary', ghost: true, onClick: () => onEdit(row), style: 'margin-right: 12px;' }, { default: () => '编辑' }),
          h(NButton, { size: 'small', type: 'error', ghost: true, onClick: () => onDelete(row) }, { default: () => '删除' })
        ]);
      },
    },
  ];
};

const handleDelete = (rowData) => {
  dialog.warning({
    title: '确认删除',
    content: `您确定要删除高校 "${rowData.schoolName}" 吗？此操作不可恢复。`,
    positiveText: '确定删除',
    negativeText: '取消',
    onPositiveClick: () => {
      // 立即关闭对话框，异步执行删除操作
      performDelete(rowData);
      return true; // 立即关闭对话框
    }
  });
};

const performDelete = async (rowData) => {
  const loadingMessage = message.loading(`正在删除高校 ${rowData.schoolName}...`, { duration: 0 });
  try {
    await universityStore.deleteUniversity(rowData._id);
    loadingMessage.destroy();
    message.success(`高校 ${rowData.schoolName} 已删除`);
    // 重新获取当前页数据
    await fetchUniversitiesWithFilters();
  } catch (error) {
    loadingMessage.destroy();
    message.error('删除失败，请重试');
    console.error("删除失败:", error);
  }
};

const columns = ref(createColumns({
  onEdit: openEditModal,
  onDelete: handleDelete,
}));

// --- Data Fetching, Filtering, Pagination, Sorting ---
const searchTerm = ref('');
const filterGoverningDepartment = ref([]);
const filterLocation = ref([]);
const filterIsCentral = ref(null);

const paginationConfig = computed(() => ({
  page: universityStore.pagination.page,
  pageSize: universityStore.pagination.limit,
  itemCount: universityStore.pagination.total,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100],
  showQuickJumper: true,
}));

const currentSortKey = ref(null);
const currentSortOrder = ref(false);
const isExporting = ref(false);



let searchDebounceTimer = null;
const handleSearchDebounced = () => {
    clearTimeout(searchDebounceTimer);
    searchDebounceTimer = setTimeout(() => {
        handleSearch();
    }, 300);
};

const handleSearch = async () => {
  await fetchUniversitiesWithFilters({ page: 1 });
};

// 获取带过滤条件的高校数据
const fetchUniversitiesWithFilters = async (paginationParams = {}) => {
  try {
    const params = {
      page: paginationParams.page || universityStore.pagination.page,
      pageSize: paginationParams.pageSize || universityStore.pagination.limit,
      search: searchTerm.value,
      location: filterLocation.value?.length > 0 ? filterLocation.value.join(',') : undefined,
      isCentral: filterIsCentral.value?.length > 0 ? filterIsCentral.value.join(',') : undefined,
      sortBy: currentSortKey.value,
      sortOrder: currentSortOrder.value === 'ascend' ? 'asc' : currentSortOrder.value === 'descend' ? 'desc' : undefined,
    };

    // 移除undefined值
    Object.keys(params).forEach(key => {
      if (params[key] === undefined || params[key] === '') {
        delete params[key];
      }
    });

    await universityStore.fetchUniversities(params);
  } catch (error) {
    console.error('获取高校数据失败:', error);
    message.error('获取数据失败');
  }
};

const applyTableFilters = async () => {
  await fetchUniversitiesWithFilters({ page: 1 });
};

const handlePageChange = async (page) => {
  await fetchUniversitiesWithFilters({ page });
};

const handlePageSizeChange = async (pageSize) => {
  await fetchUniversitiesWithFilters({ page: 1, pageSize });
};

const handleSorterChange = async (sorter) => {
  if (sorter && sorter.columnKey && sorter.order) {
    currentSortKey.value = sorter.columnKey;
    currentSortOrder.value = sorter.order;
  } else {
    currentSortKey.value = null;
    currentSortOrder.value = false;
  }
  await fetchUniversitiesWithFilters({ page: 1 });
};

// 导出功能
const handleExport = async () => {
  if (isExporting.value) return;

  try {
    isExporting.value = true;

    // 使用简单的 window.open 方式
    const exportUrl = 'http://localhost:3001/api/export/universities';
    window.open(exportUrl, '_blank');

    message.success('高校信息导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    message.error('导出失败，请重试');
  } finally {
    isExporting.value = false;
  }
};

onMounted(async () => {
  try {
    // 加载第一页高校数据
    await fetchUniversitiesWithFilters();
  } catch (error) {
    console.error("Error during initial data fetch:", error);
    message.error("初始化数据加载失败");
  }
});
</script>